import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../util/response-util";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../util/page-subject";
import {TableUtil} from "../../../util/table-util";
import {API, MsgConstants} from "../../../constants/constants";
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {MsgResult} from "../../../models/msg-result";
import {OperService} from "./oper.service";

declare var $;
declare var moment;

@Component({
  selector: 'app-oper',
  templateUrl: './oper.component.html',
  styleUrls: ['./oper.component.css']
})
export class OperComponent implements OnInit,AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;

  table;
  config;
  config2;

  operIdArr : Array<String> = [];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private operService: OperService,
    private dialogService: OneDialogService,
    private tableUtil: TableUtil,
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil
  ) {
  }

  ngOnInit() {
    this.initTime();
    //初始化面包屑导航
    this.pushPage();
    //初始化表单
    this.loadLoginLog();
  }  //end ngOnInit

  proxy = {
    "operLogDetails": () => this.operLogDetails(),
    "operLogDelete": () => this.operLogDelete()
  }

  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("系统日志", "");
    this.pageSubject.pushPage("系统日志", "操作日志查询", path);
  }

  // 刷新方法
  search() {
    this.table.bootstrapTable('refresh');
  }

  loadLoginLog() {
    this.table = this.tableUtil.load("one_table_operLog", {
      columns: [
        {checkbox:true,width:40},
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "operName", title: '操作者名称',class:"one-table-col-6", align: 'left'},
        {field: "moduleName", title: '模块名',class:"one-table-col-4", align: 'left'},
        {field: "type", title: '类型', align: 'left', formatter: this.typeFormat},
        {field: "className", title: '操作类名',class:"one-table-col-4", align: 'left',formatter: this.tableUtil.showToolTip},
        {field: "methodName", title: '操作方法名',class:"one-table-col-6", align: 'left',formatter: this.tableUtil.showToolTip},
        {field: "content", title: '日志内容',class:"one-table-col-4", align: 'left',formatter: this.tableUtil.showToolTip},
        {field: "OPERATE_TIME", title: '操作时间',class:"one-table-col-icon-4", align: 'left', sortName: "OPERATE_TIME", sortable: true,formatter: this.tableUtil.showToolTip},
        {field: "ip", title: 'ip',class:"one-table-col-4", align: 'left',formatter: this.tableUtil.showToolTip},
        {field: "params", title: '参数', align: 'left' ,class:"one-table-col-2", visible: false, formatter: this.tableUtil.showToolTipChangeLine},
        {field: "operResult", title: '操作结果',class:"one-table-col-4", align: 'left',formatter: this.tableUtil.showToolTip}
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: false,//多选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_oper",
      url: API.operLogPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.operName = $("#operName").val();
        params.moduleName = $("#moduleName").val();
        params.type = $("#type").val();
        params.startTime = $("#startTime").val();
        params.endTime = $("#endTime").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            value.OPERATE_TIME = value.operTime || '';
          });
        });
      },
      height: 700,//table高度
      sortable: true,
      sortOrder: 'desc',
      sortName: 'OPERATE_TIME',
      // search:true,//是否显示搜索框
      // searchOnEnterKey:true,//点击enter键是否触发搜索事件
      // searchText:'',//默认搜索内容
      // smartDisplay:true,//智能显示分页或card视图
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  typeFormat(value, row, index) {
    if (value == '1') {
      return '新增';
    }
    if (value == '2') {
      return '修改';
    }
    if (value == '3') {
      return '删除';
    }
    if (value == '4') {
      return '查询';
    }
  }

  //初始化日期插件
  initTime() {
    let timeData = moment().format("YYYY-MM-DD HH:mm:ss");
    let startDate = moment().subtract(7, "days").format("YYYY-MM-DD HH:mm:ss");

    this.config = {
      timePicker: true,
      timePickerIncrement: 1,
      singleDatePicker: true,
      timePicker24Hour: true,
      parentEl: $(".wrapper"),
      maxDate: moment().format("YYYY-MM-DD HH:mm:ss"),
      locale: {
        format: "YYYY-MM-DD HH:mm:ss",
        separator: " 至 ",
        applyLabel: '确定',
        cancelLabel: '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
        monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        firstDay: 1
      },
      // startDate: moment().subtract(7, "days").format("YYYY-MM-DD HH:mm:ss"),
      startDate: moment().add(5,'m').subtract(1,"days").format("YYYY-MM-DD HH:mm:ss"),
      endDate: moment().add(5,'m').format("YYYY-MM-DD HH:mm:ss")
    };
    this.config2 = {
      timePicker: true,
      timePickerIncrement: 1,
      singleDatePicker: true,
      timePicker24Hour: true,
      parentEl: $(".wrapper"),
      // maxDate:timeData,
      locale: {
        format: "YYYY-MM-DD HH:mm:ss",
        separator: " 至 ",
        applyLabel: '确定',
        cancelLabel: '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
        monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        firstDay: 1
      },
      startDate: moment().add(5,"m").format("YYYY-MM-DD HH:mm:ss"),
      endDate: moment().add(5,"m").format("YYYY-MM-DD HH:mm:ss")
    };

    $("#startTime").daterangepicker(this.config);
    $("#endTime").daterangepicker(this.config2);
  }

  /**
   * 获取单条操作日志详情
   */
  operLogDetails(){
    let row = this.table.bootstrapTable('getSelections');
    this.operIdArr = this.tableUtil.getIds(row);
    if(this.operIdArr.length != 1){
      this.dialogService.modalInfo('请选择一条数据');
    } else{
        this.router.navigate(['oper-detail',{id :this.operIdArr[0]}],{relativeTo:this.route});
    }
  }

  /**
   * 操作日志批量删除功能
   */
  operLogDelete(){
    let rows = this.table.bootstrapTable('getSelections');
    this.operIdArr=this.tableUtil.getCloumns(rows,"id");
    if (this.operIdArr.length == 0) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete);
    }
  }


  /**
   * 实现删除操作
   * 1.调取后端删除操作；
   */
  private requestDelete = () => {
    //调用后端接口
    if (this.operIdArr.length != 0 ) {
      this.operService.deleteOperLogs(this.operIdArr).subscribe(
        result => this.responseUtil.success(result, this.processDeleteResult),
        error => this.responseUtil.error(error)
      );
    }
  }

  /**
   * 处理删除结果
   * 1.判断是否删除成功；
   * @param result
   */
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.search();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
}
